import { config } from '@/settings/http';
import axios, { InternalAxiosRequestConfig, type AxiosError, type AxiosResponse } from 'axios';
import type { App } from 'vue';

export interface GlobalError {
  /** 错误码 */
  code: number;
  /** 错误信息 */
  message: string;
}

const notificationError = (error: string) => {
  console.error(error);
};

export function defaultSuccess(data: unknown): void {
  console.log(data);
}
export function defaultError(error: Error): void {
  if (error) {
    notificationError(error.message);
  }
}

const _axios = axios.create({
  baseURL: config.prefix,
  timeout: config.timeout,
});

_axios.interceptors.request.use(
  (cfg: InternalAxiosRequestConfig) => {
    return cfg;
  },
  (err: unknown) => {
    console.error(err);
    return Promise.reject(new Error('HTTP 客户端配置错误!'));
  },
);

_axios.interceptors.response.use(
  (response: AxiosResponse) => {
    return Promise.resolve(response);
  },
  (error: AxiosError<GlobalError>) => {
    switch (Number(error.response?.status)) {
      case 401:
        return Promise.reject(new Error('未登录'));
      case 403:
        return Promise.reject(new Error('没有权限'));
      case 404: {
        return Promise.reject(new Error('访问的资源不存在'));
      }
      case 500:
      default:
        return Promise.reject(new Error(error.response?.data.message));
    }
  },
);
export { _axios as http };

export default {
  install: (app: App) => {
    app.config.globalProperties.$http = _axios;
  },
};
